
package cn.net.autocode.platform.table.process;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.dbManager.Dao;


public class DataModelProcess{

    private final Dao dao;

    public DataModelProcess(Dao dao) {
        this.dao = dao;
    }


    public JSONArray process(String... tableName) {
        JSONArray tables = new JSONArray();
        if(tableName==null||tableName.length==0){
            //获取全部表
            JSONArray tableArray = dao.getTables();
            int len = tableArray.size();
            tableName = new String[len];
            for(int i=0;i<len;i++){
                String table = tableArray.getJSONObject(i).getString("tableName");
                tableName[i]=table;
            }
        }

        for (String table:tableName) {
            JSONObject tableInfo = dao.queryTableInfo(table.toLowerCase());
            JSONArray columns = tableInfo.getJSONArray("columns");
            int len = columns.size();
            for(int i=0;i<len;i++){
                JSONObject column = columns.getJSONObject(i);
                column.put("type",this.dbToApp(column.getString("type").toUpperCase()));
                if(column.getIntValue("length")>1000000000||column.getIntValue("length")<=0){
                    column.put("length",0);
                };
                column.put("name",column.getString("name").toLowerCase());
            }
            tables.add(tableInfo);
        }
        return tables;
    }


    private String dbToApp(String type){

        switch(type.toUpperCase()){
            case "TINYINT"://MYSQL
            case "SMALLINT"://MYSQL
            case "MEDIUMINT"://MYSQL
            case "BIGINT"://MYSQL
            case "INT"://MYSQL、SQLSERVER、ORACLE
                return "INT";
            case "NCHAR"://SQLSERVER
            case "CHAR"://MYSQL
                return "CHAR";
            case "TEXT"://SQLSERVER,MYSQL
            case "TINYTEXT"://,MYSQL
            case "LONGTEXT"://MYSQL
                return "TEXT";
            case "NVARCHAR"://SQLSERVER
            case "VARCHAR2"://ORACLE
            case "VARCHAR"://MYSQL
                return "VARCHAR";
            case "DECIMAL"://SQLSERVER,MYSQL
            case "FLOAT"://MYSQL
            case "DOUBLE"://MYSQL
                return "DECIMAL";
            case "YEAR"://MYSQL
            case "TIME"://MYSQL
            case "DATE"://MYSQL
            case "DATETIME"://MYSQL、SQLSERVER
                return "DATETIME";
            case "IMAGE"://SQLSERVER
            case "LONGBLOB"://MYSQL
                return "LONGBLOB";
            case "TIMESTAMP"://MYSQL、sqlserver
                return "TIMESTAMP";
            default:
                return type.toUpperCase();
        }
    }

}
